package linkedlist;

import org.junit.Test;
import static linkedlist.ListNode.*;

public class ReverseList206 {

    @Test
    public void test() {
        ListNode list1 = buildList(1, 2);
        printList(list1, "origin");
        ListNode list2 = reverseList(list1);
        printList(list2, "reversed");
    }

    public ListNode reverseList(ListNode head) {
        if (head == null || head.next == null) {
            return head;
        }
        ListNode prev = null;
        ListNode curr = head;

        // 四步曲
        while (curr != null) {
            // 暂存curr.next
            ListNode next = curr.next;

            // 反转
            curr.next = prev;

            // 右挪prev
            prev = curr;

            // 右挪curr
            curr = next;
        }
        return prev;
    }

    public ListNode reverseList2(ListNode head) {
        if (head == null || head.next == null) {
            return head;
        }
        ListNode prev = head;
        ListNode curr = prev.next;

        // this is important, otherwise will cause cycle
        prev.next = null;

        while (curr != null) {
            ListNode next = curr.next;
            curr.next = prev;

            prev = curr;
            curr = next;
        }
        return prev;
    }
}
